package com.leyou.cart.controller;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class CartController {

    @Autowired
    private CartService cartService;
    /**
     * 添加商品到购物车
     * @param cart
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> saveCart(@RequestBody Cart cart, HttpServletRequest request){
        cartService.saveCart(cart,request);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 查询用户的购物车数据
     * @param request
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<Cart>> findCarts(HttpServletRequest request){
        return ResponseEntity.ok(cartService.findCarts(request));
    }

    /**
     * 修改商品数量
     * @param skuId
     * @param num
     * @return
     */
    @PutMapping
    public ResponseEntity<Void> updateCartNum(@RequestParam(name = "id")Long skuId,
                                              @RequestParam(name = "num")Integer num){
        cartService.updateCartNum(skuId,num);
        return ResponseEntity.noContent().build();
    }

    /**
     * 删除购物车
     * @param skuId
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCart(@PathVariable(name = "id")Long skuId){
        cartService.deleteCart(skuId);
        return ResponseEntity.noContent().build();
    }

    /**
     * 登陆后的 购物车合并
     * 把未登录的购物车内容提交到服务端
     * @param cartList
     * @return
     */
    @PostMapping("/list")
    public ResponseEntity<Void> saveCartBatch(@RequestBody List<Cart> cartList){
        cartService.saveCartBatch(cartList);
        return ResponseEntity.noContent().build();
    }
}
